const adminService = require('../service/adminService')
const newsService = require('../service/newsService')

class NewsController {

  // 列表
  async index(req, res) {
    let page = +req.query.page || 1
    let pageLimit = await newsService.size()
    /* if (page < 1) page = 1
    if(page>pageLimit) page = pageLimit*/
    page = Math.max(1, Math.min(pageLimit, page))

    let data = await adminService.showUserInfo(req.session.uid)
    // 查询资讯列表数据
    let newsData = await newsService.index(page)
    res.render('news/index.html', { data, news: newsData, page })
  }

  // 添加用户
  async create(req, res) {
    let data = await adminService.showUserInfo(req.session.uid)
    res.render('news/create.html', { data })
  }
  async store(req, res) {
    // 进行后端验证
    let data = await newsService.create(req.body)
    res.redirect('/news/index')
  }

  async edit(req, res) {
    let data = await adminService.showUserInfo(req.session.uid)
    let id = req.params.id
    let newsData = await newsService.getIdToInfo(id)
    res.render('news/edit.html', { data, newsData, id })
  }

  async update(req, res) {
    let id = req.params.id
    let data = req.body
    await newsService.update(id, data)
    res.redirect('/news/index')
  }

  // 软删除，逻辑删除 isdel=false
  async del(req, res) {
    await newsService.destory(req.params.id)
    res.send({ code: 0 })
  }


}

module.exports = new NewsController()
